<template>
  <div style="width: 100%; height: 100%">
    <!-- 查询框 -->
    <div>
      <el-tag>标题</el-tag>
      <el-input v-model="keyword" style="width: 300px; margin-left: 10px; margin-right: 10px" placeholder="请输入关键词"></el-input>
      <el-button type="primary" @click="fetchAnnouncements">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>

    <!-- 操作框 -->
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 公告列表 -->
    <!-- 表格 -->
    <div style="margin: 10px 0">
      <el-table :data="announcements" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="announcement_id" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="content" label="内容"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.announcement_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑公告模态框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="editItem" label-width="100px" :rules="rule">
        <el-form-item label="标题">
          <el-input v-model="editItem.title"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="editItem.content"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">{{ isEditing ? '保存' : '新增' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      keyword: '', // 查询关键词
      announcements: [], // 公告信息列表
      currentPage: 1, // 当前页数
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      dialogVisible: false, // 公告信息模态框可见性
      editItem: { // 编辑/新增的数据
        announcement_id: '',
        title: '',
        content: '',
        posted_by:''
      },
      user:JSON.parse(localStorage.getItem('userData')) || {},
      isEditing: false, // 是否为新增模式
      rule: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'}
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      return this.isEditing ? '编辑信息' : '新增信息';
    }
  },
  mounted() {
    this.fetchAnnouncements();
  },
  methods: {
    // 获取公告信息
    fetchAnnouncements() {
      let url = 'http://localhost:8080/Announcements/selectAll';
      let params = {
        page: this.currentPage,
        size: this.pageSize
      };

      if (this.keyword) {
        axios.get('http://localhost:8080/Announcements/selectByTitle', {
          params: {
            title: this.keyword
          }
        })
            .then(response => {
              this.announcements = response.data.data;
            })
            .catch(error => {
              console.error('Error fetching announcements:', error);
            });
      } else {
        axios.get(url, {params})
            .then(response => {
              const data = response.data.data;
              this.announcements = data;
              this.totalItems = data.length;
            })
            .catch(error => {
              console.error('Error fetching announcements:', error);
            });
      }
    },
    reset() {
      this.keyword = '';
      this.currentPage = 1;
      this.pageSize = 5;
      this.fetchAnnouncements();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchAnnouncements();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchAnnouncements();
    },
    handleSelectionChange(val) {
      this.selectedRows = val.map(row => row.announcement_id);
    },
    showAddDialog() {
      this.isEditing = false;
      this.editItem = {
        announcement_id: '',
        title: '',
        content: ''
      };
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.isEditing = false;
    },
    handleAdd() {
      this.editItem.posted_by=this.user.user_id
      axios.post("http://localhost:8080/Announcements/add", this.editItem)
          .then(response => {
            this.$message.success("新增成功");
            this.dialogVisible = false;
            this.fetchAnnouncements();
          })
          .catch(error => {
            console.error('Error adding new item:', error);
            this.$message.error("新增失败");
          });
    },
    handleEdit(row) {
      this.editItem = Object.assign({}, row);
      this.isEditing = true;
      this.dialogVisible = true;
    },
    handleSaveEdit() {
      if (this.isEditing) {
        axios.put("http://localhost:8080/Announcements/edit", this.editItem)
            .then(response => {
              this.$message.success("编辑成功");
              this.closeDialog();
              this.fetchAnnouncements();
            })
            .catch(error => {
              console.error('Error editing item:', error);
              this.$message.error("编辑失败");
            });
      } else {
        this.handleAdd();
      }
    },
    handleDelete(announcement_id) {
      this.$confirm('此操作将永久删除该条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/Announcements/delete/${announcement_id}`)
            .then(response => {
              this.$message.success('删除成功');
              this.fetchAnnouncements();
            })
            .catch(error => {
              console.error('Error deleting item:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    delBatch() {
      this.$confirm('此操作将永久删除所选条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/Announcements/deleteBatch`, {data: this.selectedRows})
            .then(response => {
              this.$message.success('批量删除成功');
              this.fetchAnnouncements();
              this.selectedRows = [];
            })
            .catch(error => {
              console.error('Error deleting batch:', error);
              this.$message.error('批量删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消批量删除');
      });
    }
  }
};
</script>

<style scoped>
.table-container {
  margin-top: 20px;
}
</style>
